from Connections import StatefulConnection

class ConnectionTable(object):
    def __init__(self):
        self.table = {}

    def get_playing(self):
        return [c for c in self.table.itervalues() if c.is_logged_in()]

    def add_to_group(self, transport):
        try:
            sc = StatefulConnection(transport)
            self.table[transport.fileno()] = sc
        except Exception, e:
            print e
            transport.loseConnection()

    def remove(self, transport):
        sc = self.table.pop(transport.fileno(), None)
        del sc

    def receive_line(self, transport, line):
        self.table[transport.fileno()].receive_line(line)

    def broadcast(self, message, transport=None):
        for sc in self.get_playing():
            if sc.transport is not transport:
                sc.to_self("\n%s" % message, True)
            else:
                sc.to_self("%s" % message.strip())

    def is_logged_in(self, username):
        return any(
                username == sc.username and
                sc.is_logged_in()
                for sc in self.table.itervalues())
